package com.platform.pdf;

import com.platform.comm.exceptions.RestApiException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

/**
 * @author qijunyu
 */
@Component
public class HtmlGenerator {

    private FreeMarkerConfigurer fmc;

    public HtmlGenerator(FreeMarkerConfigurer fmc) {
        this.fmc = fmc;
    }

    /**
     * Generate html string.
     *
     * @param template  the name of freemarker teamlate.
     * @param variables the data of teamlate.
     * @return htmlStr
     */
    String generate(String template, Object variables) throws IOException, TemplateException {
        BufferedWriter writer = null;
        String htmlContent;
        try {
            Configuration config = fmc.getConfiguration();
            Template tp = config.getTemplate(template, "UTF-8");
            StringWriter stringWriter = new StringWriter();
            writer = new BufferedWriter(stringWriter);
            tp.process(variables, writer);
            htmlContent = stringWriter.toString();
            writer.flush();

        } catch (TemplateNotFoundException e) {
            throw new RestApiException("未找到报告样式：" + template);
        } catch (Exception e) {
            throw new RestApiException("生成错误");
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        return htmlContent;
    }

}
